package com.tronsis.distribution.activity.me.agent;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageAndVideoPreviewSeeActivity;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.tronsis.distribution.R;
import com.tronsis.distribution.activity.me.address.AddressManageActivity;
import com.tronsis.distribution.bean.AddressBean;
import com.tronsis.distribution.bean.AgentExitBean;
import com.tronsis.distribution.bean.RulesMapBean;
import com.tronsis.distribution.bean.UploadFileBean;
import com.tronsis.distribution.bean.UserBean;
import com.tronsis.distribution.biz.factory.FileBizFactory;
import com.tronsis.distribution.biz.factory.OrderBizFactory;
import com.tronsis.distribution.biz.factory.ResourceBizFactory;
import com.tronsis.distribution.biz.factory.UpgradeBizFactory;
import com.tronsis.distribution.biz.factory.UserBizFactory;
import com.tronsis.distribution.http.Url;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.distribution.util.GlideImageLoader;
import com.tronsis.distribution.util.StateUtil;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.imageloader.ImageLoader;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.util.WindowUtil;
import com.tronsis.library.widget.ConfirmDialog;

import java.io.File;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.lzy.imagepicker.ImagePicker.REQUEST_CODE_PREVIEW;

public class AgentExitActivity extends ToolBarBaseActivity {

    @BindView(R.id.spinner_is_clear)
    AppCompatSpinner mSpinnerIsClear;
    @BindView(R.id.spinner_type)
    AppCompatSpinner mSpinnerType;
    @BindView(R.id.tv_view)
    TextView mTvView;
    @BindView(R.id.tv_price)
    TextView mTvPrice;
    @BindView(R.id.tv_add_address)
    TextView mTvAddAddress;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_phone)
    TextView mTvPhone;
    @BindView(R.id.tv_address)
    TextView mTvAddress;
    @BindView(R.id.tv_profit)
    TextView mTvProfit;
    @BindView(R.id.tv_total_type)
    TextView mTvTotalType;
    @BindView(R.id.tv_pay_money)
    TextView mTvPayMoney;
    @BindView(R.id.tv_info_profit)
    TextView mTvInfoProfit;
    @BindView(R.id.tv_info_total_type)
    TextView mTvInfoTotalType;
    @BindView(R.id.tv_info_pay_money)
    TextView mTvInfoPayMoney;
    @BindView(R.id.tv_rule_tag)
    TextView mTvRuleTag;
    @BindView(R.id.tv_rule)
    TextView mTvRule;
    @BindView(R.id.tv_state_tips)
    TextView mTvStateTips;
    @BindView(R.id.tv_info_is_clear)
    TextView mTvInfoIsClear;
    @BindView(R.id.tv_info_clear_type)
    TextView mTvInfoClearType;
    @BindView(R.id.tv_info_view)
    TextView mTvInfoView;
    @BindView(R.id.tv_info_price)
    TextView mTvInfoPrice;
    @BindView(R.id.tv_info_name)
    TextView mTvInfoName;
    @BindView(R.id.tv_info_phone)
    TextView mTvInfoPhone;
    @BindView(R.id.tv_info_address)
    TextView mTvInfoAddress;
    @BindView(R.id.ll_clear)
    LinearLayout mLlClear;
    @BindView(R.id.ll_money)
    LinearLayout mLlMoney;
    @BindView(R.id.ll_info_money)
    LinearLayout mLlInfoMoney;
    @BindView(R.id.ll_order_price)
    LinearLayout mLlOrderPrice;
    @BindView(R.id.ll_address_info)
    LinearLayout mLlAddressInfo;
    @BindView(R.id.ll_exit_apply)
    LinearLayout mllExitApply;
    @BindView(R.id.ll_detail)
    LinearLayout mllDetail;
    @BindView(R.id.ll_address_select)
    LinearLayout mAddressSelect;
    @BindView(R.id.btn_apply_exit)
    Button mBtnApplyExit;
    @BindView(R.id.btn_confirm)
    Button mBtnConfirm;
    @BindView(R.id.btn_update)
    Button mBtnUpdate;
    @BindView(R.id.ll_clear_type)
    LinearLayout mLlClearType;
    @BindView(R.id.ll_product_view)
    LinearLayout mLlProductView;
    @BindView(R.id.ll_product_price)
    LinearLayout mLlProductPrice;
    @BindView(R.id.ll_receive_info)
    LinearLayout mLlReceiveInfo;
    @BindView(R.id.rv_deposit_image)
    RecyclerView mRvDeposit;
    @BindView(R.id.rv_payment_image)
    RecyclerView mRvPayment;
    @BindView(R.id.rv_deliver_image)
    RecyclerView mRvDeliver;
    @BindView(R.id.tv_label_deal)
    TextView mTvLabelDeal;
    @BindView(R.id.tv_label_deposit_image)
    TextView mTvLabelDepositImage;
    @BindView(R.id.tv_label_payment_image)
    TextView mTvLabelPaymentImage;
    @BindView(R.id.tv_label_express)
    TextView mTvLabelExpress;
    @BindView(R.id.tv_express_company)
    TextView mTvExpressCompany;
    @BindView(R.id.tv_express_num)
    TextView mTvExpressNum;
    @BindView(R.id.tv_express_price)
    TextView mTvExpressPrice;
    @BindView(R.id.tv_label_deliver_image)
    TextView mTvLabelDeliverImage;
    @BindView(R.id.ll_express)
    LinearLayout mLlExpress;
    @BindView(R.id.tv_label_pay_image)
    TextView mTvLabelPayImage;
    @BindView(R.id.rv_pay_image)
    RecyclerView mRvPay;

    private ArrayList<ImageItem> mDepositImageList = new ArrayList<>();
    private ArrayList<ImageItem> mPayImageList = new ArrayList<>();
    private ArrayList<ImageItem> mDeliverImageList = new ArrayList<>();
    private CommonAdapter<ImageItem> mDepositAdapter;
    private CommonAdapter<ImageItem> mPayAdapter;
    private CommonAdapter<ImageItem> mDeliverAdapter;

    private String mAddressId;
    private String mType;
    private String isClear;
    private AgentExitBean mAgentExitBean;
    private Double profitMoney;


//    private static final int REQUEST_CAMERA = 125;
//    private static final int REQUEST_ALBUM = 126;
//    private static final int REQUEST_VIDEO = 127;
//    private PopupWindow mTypePopupWindow;
//    private PopupWindow mPopupWindow;
//    private boolean mShowDelete = false;
//    private CommonAdapter<ImageItem> mCustomImageAdapter;
//    private ArrayList<ImageItem> mImageList = new ArrayList<>();
//    private ImageItem mImageItem = new ImageItem();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_agent_exit);
        ButterKnife.bind(this);
        setTitle(true, getString(R.string.exit_agent));
        UserBean loginUser = UserBizFactory.createBiz().getLoginUser(mContext);

        initIsClearSpinner((loginUser.getStock() > 0));
//        initClearTypeSpinner();
        initImageRv();
//        initPaymentImageRv();
        RulesMapBean rulesMapBean = CommonUtil.getRulesMap(this);
        if (rulesMapBean != null && rulesMapBean.getRULE_UPGRADE() != null) {
            mTvRule.setText(rulesMapBean.getRULE_EXIT());
        }
        httpGetUserInfo();
        httpGetExitDetail();
//        httpGetPrice();
//        httpGetProfit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            AddressBean addressBean = (AddressBean) data.getSerializableExtra("AddressBean");
            if (addressBean != null) {
                mAddressSelect.setVisibility(View.VISIBLE);
                mTvName.setText(getString(R.string.format_deliver_name, addressBean.getName()));
                mTvPhone.setText(addressBean.getPhone());
                mTvAddress.setText(CommonUtil.getRegionString(addressBean.getRegion()) + addressBean.getDetail());
                mAddressId = addressBean.getId();
            }
        }
//        if (resultCode == ImagePicker.RESULT_CODE_ITEMS && data != null) {
//            List<ImageItem> imageItems = (List<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
//            if (imageItems != null && imageItems.size() > 0) {
//                mImageList.remove(mImageItem);
//                mImageList.addAll(imageItems);
//                if (mImageList.size() < 3) {
//                    mImageList.add(mImageItem);
//                }
//                mCustomImageAdapter.notifyDataSetChanged();
//            }
//        }
    }

    private void initIsClearSpinner(boolean isHasStock) {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, R.layout.layout_textview_13);
        adapter.add("请选择");
        if (isHasStock) {
            adapter.add("是");
        }
        adapter.add("否");
        mSpinnerIsClear.setAdapter(adapter);

        mSpinnerIsClear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    isClear = null;
                    mAddressId = null;
                    mLlClear.setVisibility(View.GONE);
//                    mLlMoney.setVisibility(View.GONE);
                    mSpinnerType.setSelection(0);
                }

                String select = (String) mSpinnerIsClear.getSelectedItem();
                if (StringUtil.isEquals(select, "是")) {
                    isClear = "true";
                    mLlClear.setVisibility(View.VISIBLE);
                    mType = StateUtil.AGENT_QUIT_TYPE_DELIVERY;
                    mLlAddressInfo.setVisibility(View.VISIBLE);
//                    mSpinnerType.setSelection(0);
                }
                if (StringUtil.isEquals(select, "否")) {
                    isClear = "false";
                    mAddressId = null;
                    mLlClear.setVisibility(View.GONE);
//                    mLlMoney.setVisibility(View.VISIBLE);
//                    mSpinnerType.setSelection(0);
//                    httpGetProfit();
                }

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    private void initClearTypeSpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(mContext, R.layout.layout_textview_13);
        adapter.add("请选择");
        adapter.add("发货");
        adapter.add("退还库存");
        mSpinnerType.setAdapter(adapter);

        mSpinnerType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    mType = null;
                    mLlOrderPrice.setVisibility(View.GONE);
                    mLlAddressInfo.setVisibility(View.GONE);
//                    mLlMoney.setVisibility(View.GONE);
                }

                if (position == 1) {
                    mType = StateUtil.AGENT_QUIT_TYPE_DELIVERY;
                    mLlOrderPrice.setVisibility(View.GONE);
                    mLlAddressInfo.setVisibility(View.VISIBLE);
//                    mLlMoney.setVisibility(View.VISIBLE);
//                    httpGetProfit();
                }

                if (position == 2) {
                    mType = StateUtil.AGENT_QUIT_TYPE_RETURN;
                    mLlOrderPrice.setVisibility(View.GONE);
                    mLlAddressInfo.setVisibility(View.GONE);
//                    mLlMoney.setVisibility(View.VISIBLE);
//                    httpGetPrice();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    private void initImageRv() {
        mDepositAdapter = new CommonAdapter<ImageItem>(mContext, mDepositImageList, R.layout.item_grid_image_view) {
            @Override
            protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                ImageView ivItem = holder.getView(R.id.iv_item);
                if (TextUtils.isEmpty(imageItem.url)) {
                    ImageLoader.display(mContext, new File(imageItem.path), ivItem);
                }

                if (TextUtils.isEmpty(imageItem.path)) {
                    ImageLoader.display(mContext, imageItem.url, ivItem);
                }

                ivItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(mDepositImageList.get(position).path) && TextUtils.isEmpty(mDepositImageList.get(position).url)) {
                            return;
                        }
                        Intent intentPreview = new Intent(mContext, ImageAndVideoPreviewSeeActivity.class);
                        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                        intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mDepositImageList);
                        startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                    }
                });
            }


        };
        mRvDeposit.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRvDeposit.setAdapter(mDepositAdapter);
        mRvDeposit.setHasFixedSize(true);
        mRvDeposit.setNestedScrollingEnabled(false);

        mPayAdapter = new CommonAdapter<ImageItem>(mContext, mPayImageList, R.layout.item_grid_image_view) {
            @Override
            protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                ImageView ivItem = holder.getView(R.id.iv_item);
                if (TextUtils.isEmpty(imageItem.url)) {
                    ImageLoader.display(mContext, new File(imageItem.path), ivItem);
                }

                if (TextUtils.isEmpty(imageItem.path)) {
                    ImageLoader.display(mContext, imageItem.url, ivItem);
                }

                ivItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(mPayImageList.get(position).path) && TextUtils.isEmpty(mPayImageList.get(position).url)) {
                            return;
                        }
                        Intent intentPreview = new Intent(mContext, ImageAndVideoPreviewSeeActivity.class);
                        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                        intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mPayImageList);
                        startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                    }
                });
            }


        };
        mRvPay.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRvPay.setAdapter(mPayAdapter);
        mRvPay.setHasFixedSize(true);
        mRvPay.setNestedScrollingEnabled(false);

        mDeliverAdapter = new CommonAdapter<ImageItem>(mContext, mDeliverImageList, R.layout.item_grid_image_view) {
            @Override
            protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
                ImageView ivItem = holder.getView(R.id.iv_item);
                if (TextUtils.isEmpty(imageItem.url)) {
                    ImageLoader.display(mContext, new File(imageItem.path), ivItem);
                }

                if (TextUtils.isEmpty(imageItem.path)) {
                    ImageLoader.display(mContext, imageItem.url, ivItem);
                }

                ivItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(mDeliverImageList.get(position).path) && TextUtils.isEmpty(mDeliverImageList.get(position).url)) {
                            return;
                        }
                        Intent intentPreview = new Intent(mContext, ImageAndVideoPreviewSeeActivity.class);
                        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                        intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mDeliverImageList);
                        startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                    }
                });
            }


        };


        mRvDeliver.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRvDeliver.setAdapter(mDeliverAdapter);
        mRvDeliver.setHasFixedSize(true);
        mRvDeliver.setNestedScrollingEnabled(false);
    }

    @OnClick({R.id.tv_view, R.id.tv_info_view})
    void stockViewClick() {
        Intent intent = new Intent(mContext, AgentExitGoodsActivity.class);
        if (mAgentExitBean != null) {
            intent.putExtra("quitId", mAgentExitBean.getId());
        }
        startActivity(intent);
    }

    @OnClick(R.id.tv_add_address)
    void addAddressClick() {
        Intent intent = new Intent(mContext, AddressManageActivity.class);
        intent.setType("select");
        startActivityForResult(intent, 0x176);
    }

    @OnClick(R.id.btn_apply_exit)
    void exitApplyClick() {
        if (TextUtils.isEmpty(isClear)) {
            ToastUtil.showMessage(mContext, "请选择是否清理库存");
            return;
        }

        if (Boolean.valueOf(isClear) && StringUtil.isEquals(mType, StateUtil.AGENT_QUIT_TYPE_DELIVERY) && TextUtils.isEmpty(mAddressId)) {
            ToastUtil.showMessage(mContext, "请选择地址");
            return;
        }

        httpExitApply(mAddressId, isClear, mType);
    }

    @OnClick(R.id.btn_confirm)
    void exitConfirmClick() {
        new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
            @Override
            public void onLeftButtonClick(View view) {

            }

            @Override
            public void onRightButtonClick(View view) {
                httpExitConfirm();
            }
        }).showDialog("确定后将会退出登录", "取消", "确定");


    }

//    //Allen: 上传付款凭证
//    @OnClick(R.id.btn_update)
//    void updateClick() {
//        final ArrayList<File> fileList = new ArrayList<>();
//        final ArrayList<String> idList = new ArrayList<>();
//        if (mImageList.size() == 1) {
//            ToastUtil.showToastInCenter(mContext, "请上传付款凭证");
//            return;
//        }
//        for (ImageItem imageItem : mImageList) {
//            if (!TextUtils.isEmpty(imageItem.path)) {
//                fileList.add(new File(imageItem.path));
//            }
//        }
//
//        try {
//            FileBizFactory.createBiz().uploads(this, fileList, Url.FILE_TYPE_IMAGE, new UICallBack() {
//                @Override
//                public void onStart() {
//                    showLoadingDialog();
//                }
//
//                @Override
//                public void onRefresh(Object data) {
//                    List<UploadFileBean> fileBeanList = (List<UploadFileBean>) data;
//                    List<String> fileIds = new ArrayList<>();
//                    for (ImageItem imageItem : mImageList) {
//                        if (!TextUtils.isEmpty(imageItem.url)) {
//                            fileIds.add(imageItem.url);
//                        }
//                    }
//                    for (UploadFileBean uploadFileBean : fileBeanList) {
//                        fileIds.add(uploadFileBean.getId());
//                    }
//
//                    String ids = StringUtil.arrayList(fileIds);
//                    addQuitProfit(ids);
//
//                }
//
//                @Override
//                public void onFailure(int status) {
//                    dismissLoadingDialog();
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//            dismissLoadingDialog();
//        }
//
//
//    }
//
//    private void addQuitProfit(String arrayList) {
//        try {
//            ResourceBizFactory.createBiz().addQuitProfit(this,mAgentExitBean.getId(), arrayList, new UICallBack() {
//                @Override
//                public void onStart() {
//                    showLoadingDialog();
//                }
//
//                @Override
//                public void onRefresh(Object data) {
//                    dismissLoadingDialog();
//                    finish();
//                }
//
//                @Override
//                public void onFailure(int status) {
//                    dismissLoadingDialog();
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//            dismissLoadingDialog();
//
//        }
//    }

    private void httpGetExitDetail() {
        try {
            UpgradeBizFactory.createBiz().quitDetail(this, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    mAgentExitBean = (AgentExitBean) data;
                    setDetailView(mAgentExitBean);

                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setDetailView(AgentExitBean bean) {
        if (bean == null) {
            mllExitApply.setVisibility(View.VISIBLE);
            mllDetail.setVisibility(View.GONE);
            mBtnApplyExit.setVisibility(View.VISIBLE);
            return;
        }

        mllExitApply.setVisibility(View.GONE);
        mllDetail.setVisibility(View.VISIBLE);
        mBtnApplyExit.setVisibility(View.GONE);
        boolean isClear = bean.isClear();
        String clearType = bean.getClearType();
//        Double total;
//        BigDecimal goodPriceBd = new BigDecimal(Double.toString(bean.getStockPrice()));
//        BigDecimal profitMoneyBd = new BigDecimal(Double.toString(bean.getMoney()));
//        if (bean.getMoney() > bean.getStockPrice()) {
//            total = profitMoneyBd.subtract(goodPriceBd).doubleValue();
//            mTvInfoTotalType.setText("上缴金额：");
//        } else {
//            total = goodPriceBd.subtract(profitMoneyBd).doubleValue();
//            mTvInfoTotalType.setText("退还金额：");
//        }
//        mTvInfoPayMoney.setText(getString(R.string.format_price, total));
//        mTvInfoProfit.setText(getString(R.string.format_price, bean.getMoney()));
        mTvInfoIsClear.setText(isClear ? "是" : "否");
        if (isClear) {
//            mLlClearType.setVisibility(View.VISIBLE);
            mLlProductView.setVisibility(View.VISIBLE);
            if (StringUtil.isEquals(clearType, StateUtil.AGENT_QUIT_TYPE_RETURN)) {
//                mTvInfoClearType.setText("退还库存");
                mTvInfoPrice.setText(getString(R.string.format_price, bean.getStockPrice()));
                mLlProductPrice.setVisibility(View.GONE);
                mLlReceiveInfo.setVisibility(View.GONE);
                mLlExpress.setVisibility(View.GONE);
            } else {
//                mTvInfoClearType.setText("发货");
                mLlProductPrice.setVisibility(View.GONE);
                mLlReceiveInfo.setVisibility(View.VISIBLE);
                mLlExpress.setVisibility(View.VISIBLE);
                AddressBean receiverAddr = bean.getReceiverAddr();
                if (receiverAddr != null) {
                    mTvInfoName.setText(receiverAddr.getName());
                    mTvInfoPhone.setText(receiverAddr.getPhone());
                    mTvInfoAddress.setText(CommonUtil.getRegionString(receiverAddr.getRegion()) + receiverAddr.getDetail());
                }
            }
        } else {
            mLlClearType.setVisibility(View.GONE);
            mLlProductView.setVisibility(View.GONE);
            mLlProductPrice.setVisibility(View.GONE);
            mLlReceiveInfo.setVisibility(View.GONE);
        }


        if (bean.getDepositFid() != null) {
            mTvLabelDeal.setVisibility(View.VISIBLE);
            mTvLabelDepositImage.setVisibility(View.VISIBLE);
            mRvDeposit.setVisibility(View.VISIBLE);
            mDepositImageList.clear();
            mDepositImageList.addAll(CommonUtil.getSplitImage(bean.getDepositFid()));
            mDepositAdapter.notifyDataSetChanged();
        } else {
            mTvLabelDepositImage.setVisibility(View.GONE);
            mRvDeposit.setVisibility(View.GONE);
        }

        if (bean.getStockFid() != null) {
            mTvLabelPayImage.setVisibility(View.VISIBLE);
            mRvPay.setVisibility(View.VISIBLE);
            mPayImageList.clear();
            mPayImageList.addAll(CommonUtil.getSplitImage(bean.getStockFid()));
            mPayAdapter.notifyDataSetChanged();
        } else {
            mTvLabelPayImage.setVisibility(View.GONE);
            mRvPay.setVisibility(View.GONE);
        }

        if (bean.getExpressFid() != null) {
            mTvLabelDeliverImage.setVisibility(View.VISIBLE);
            mRvDeliver.setVisibility(View.VISIBLE);
            mDeliverImageList.clear();
            mDeliverImageList.addAll(CommonUtil.getSplitImage(bean.getExpressFid()));
            mDeliverAdapter.notifyDataSetChanged();

            mLlExpress.setVisibility(View.VISIBLE);
            mTvExpressCompany.setText("物流公司：" + bean.getExpressInc());
            mTvExpressNum.setText("物流编号：" + bean.getExpressCode());
            mTvExpressPrice.setText("实际物流费：" + getString(R.string.format_price, bean.getRealFreight()));
        } else {
            mTvLabelDeliverImage.setVisibility(View.GONE);
            mRvDeliver.setVisibility(View.GONE);
            mLlExpress.setVisibility(View.GONE);
        }

        String state = bean.getState();
        if (state != null) {
            //退代理状态 VERIFY(待审核), HANDLE(待处理), CONFIRM(待确认), FINISH(已完成), REJECT(未通过)
            switch (state) {
                case StateUtil.AGENT_EXIT_VERIFY:
                    mTvStateTips.setVisibility(View.VISIBLE);
                    mTvStateTips.setText("该退出代理申请正在审核中，请耐心等待。");
                    mTvLabelDeal.setVisibility(View.GONE);
                    break;
                case StateUtil.AGENT_EXIT_HANDLE:
                    mTvStateTips.setVisibility(View.VISIBLE);
                    mTvStateTips.setText("该退出代理申请已通过审核正在处理中，请耐心等待。");
                    if (bean.getStockFid() != null || bean.getReceiverAddr() != null) {
                        mTvLabelDeal.setVisibility(View.VISIBLE);
                    } else {
                        mTvLabelDeal.setVisibility(View.GONE);
                    }
//                    //Allen： 需添加付款凭证
//                    if (bean.getMoney() > 0) {
//                        mTvLabelPaymentImage.setVisibility(View.VISIBLE);
//                        mRvPayment.setVisibility(View.VISIBLE);
//                        if (bean.getPriceFid() == null) {
//                            mTvStateTips.setText("该退出代理申请已通过审核，请上传付款凭证。");
//                            mTvLabelDeal.setVisibility(View.GONE);
//                            mBtnUpdate.setVisibility(View.VISIBLE);
//                        } else {
//                            mTvLabelPaymentImage.setText("付款凭证：");
//                            ArrayList<ImageItem> splitImage = CommonUtil.getSplitImage(bean.getPriceFid());
//                            mImageList.clear();
//                            mImageList.addAll(splitImage);
//                            mCustomImageAdapter.notifyDataSetChanged();
//                        }
//                    }


                    break;
                case StateUtil.AGENT_EXIT_CONFIRM:
                    //待确认
                    mTvStateTips.setVisibility(View.GONE);
                    if (bean.getStockFid() != null || bean.getReceiverAddr() != null) {
                        mTvLabelDeal.setVisibility(View.VISIBLE);
                    } else {
                        mTvLabelDeal.setVisibility(View.GONE);
                    }
                    mBtnConfirm.setVisibility(View.VISIBLE);
                    break;
                case StateUtil.AGENT_EXIT_FINISH:
                    if (bean.getStockFid() != null || bean.getReceiverAddr() != null) {
                        mTvLabelDeal.setVisibility(View.VISIBLE);
                    } else {
                        mTvLabelDeal.setVisibility(View.GONE);
                    }
                    break;
                case StateUtil.AGENT_EXIT_REJECT:
                    //已拒绝
                    mTvLabelDeal.setVisibility(View.GONE);
                    mllExitApply.setVisibility(View.VISIBLE);
                    mBtnApplyExit.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
        }


    }


    private void httpExitApply(String addressId, String isClear, String type) {
        if (!Boolean.valueOf(isClear)) {
            type = null;
            addressId = null;
        }

        if (StringUtil.isEquals(type, StateUtil.AGENT_QUIT_TYPE_RETURN)) {
            addressId = null;
        }

        try {
//            UpgradeBizFactory.createBiz().quitApply(this, addressId, isClear, profitMoney, type, new UICallBack() {
            UpgradeBizFactory.createBiz().quitApply(this, addressId, isClear, type, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    mBtnApplyExit.setVisibility(View.GONE);
                    httpGetExitDetail();
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }


    private void httpExitConfirm() {
        try {
            UpgradeBizFactory.createBiz().quitConfirm(this, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    ToastUtil.showMessage(mContext, "确认成功");
                    mBtnConfirm.setVisibility(View.GONE);
                    UserBizFactory.createBiz().logout(AgentExitActivity.this);
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }


    private void httpGetUserInfo() {
        try {
            UserBizFactory.createBiz().getUserInfo(this, new UICallBack() {
                @Override
                public void onStart() {

                }

                @Override
                public void onRefresh(Object data) {
                    UserBean userBean = (UserBean) data;
                    if (userBean != null) {
                        initIsClearSpinner((userBean.getStock() > 0));
                    }
                }

                @Override
                public void onFailure(int status) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void httpGetPrice() {
        try {
            OrderBizFactory.createBiz().getStockTotalPrice(this, new UICallBack() {
                @Override
                public void onStart() {
                    showLoadingDialog();
                }

                @Override
                public void onRefresh(Object data) {
                    dismissLoadingDialog();
                    Double d = (Double) data;
                    if (d != null) {
                        mTvPrice.setText(getString(R.string.format_price, d));
                    }
//                    Double goodPrice = (Double) data;
//                    BigDecimal goodPriceBd = new BigDecimal(Double.toString(goodPrice));
//                    BigDecimal profitMoneyBd = new BigDecimal(Double.toString(profitMoney));
//                    Double total;
//                    if (goodPrice != null) {
//                        if (profitMoney > goodPrice) {
//                            total = profitMoneyBd.subtract(goodPriceBd).doubleValue();
//                            mTvTotalType.setText("上缴金额：");
//                        } else {
//                            total = goodPriceBd.subtract(profitMoneyBd).doubleValue();
//                            mTvTotalType.setText("退还金额：");
//                        }
//                        mTvPayMoney.setText(getString(R.string.format_price, total));
//                        mTvPrice.setText(getString(R.string.format_price, goodPrice));
//                    }
                }

                @Override
                public void onFailure(int status) {
                    dismissLoadingDialog();
                }
            });
        } catch (Exception e) {
            dismissLoadingDialog();
            e.printStackTrace();
        }
    }

//    //Allen: 获取下级库存利润差价
//    private void httpGetProfit() {
//        try {
//            OrderBizFactory.createBiz().getProfit(this, new UICallBack() {
//                @Override
//                public void onStart() {
//                    showLoadingDialog();
//                }
//
//                @Override
//                public void onRefresh(Object data) {
//                    dismissLoadingDialog();
//                    profitMoney = (Double) data;
//                    if (profitMoney != null) {
//                        mTvTotalType.setText("上缴金额：");
//                        mTvProfit.setText(getString(R.string.format_price, profitMoney));
//                        mTvPayMoney.setText(getString(R.string.format_price, profitMoney));
//                    }
//                }
//
//                @Override
//                public void onFailure(int status) {
//                    dismissLoadingDialog();
//                }
//            });
//        } catch (Exception e) {
//            dismissLoadingDialog();
//            e.printStackTrace();
//        }
//    }
//
//    //Allen: 初始化上传付款凭证图片布局
//    private void initPaymentImageRv() {
//        mImageItem.path = "";
//        mImageItem.addTime = System.currentTimeMillis();
//        if (mImageList.size() < 1) {
//            mImageList.add(mImageItem); // 插入 + 号占位数据
//        }
//        mCustomImageAdapter = new CommonAdapter<ImageItem>(mContext, mImageList, R.layout.item_grid_image_view) {
//            @Override
//            protected void convert(final ViewHolder holder, final ImageItem imageItem, final int position) {
//                ImageView ivItem = (ImageView) holder.getView(R.id.iv_item);
//                holder.getView(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        showDeleteConfirmDialog(position);
//                    }
//                });
//
//                if (TextUtils.isEmpty(imageItem.path) && TextUtils.isEmpty(imageItem.url)) {
//                    holder.getView(R.id.iv_delete).setVisibility(View.GONE);
//                    ivItem.setImageResource(R.drawable.icon_add_res);
//                    ivItem.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            showPopupWindow();
//                        }
//                    });
//                } else {
//                    if (TextUtils.isEmpty(imageItem.path)) {
//                        ImageLoader.display(mContext, imageItem.url, ivItem);
//                    }
//                    if (TextUtils.isEmpty(imageItem.url)) {
//                        ImageLoader.display(mContext, new File(imageItem.path), ivItem);
//                    }
//
//                    ivItem.setOnLongClickListener(new View.OnLongClickListener() {
//                        @Override
//                        public boolean onLongClick(View v) {
//                            if (mShowDelete) {
//                                mShowDelete = false;
//                            } else {
//                                mShowDelete = true;
//                            }
//                            notifyDataSetChanged();
//                            return false;
//                        }
//                    });
//
//                    ivItem.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            if (TextUtils.isEmpty(mImageList.get(position).path) && TextUtils.isEmpty(mImageList.get(position).url)) {
//                                return;
//                            }
//
//                            if (mImageList.contains(mImageItem)) {
//                                mImageList.remove(mImageItem);
//                            }
//
//                            Intent intentPreview = new Intent(AgentExitActivity.this, ImageAndVideoPreviewSeeActivity.class);
//                            intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
//                            intentPreview.putParcelableArrayListExtra(ImagePicker.EXTRA_IMAGE_ITEMS, mImageList);
//                            startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
//                        }
//                    });
//
//                    if (mShowDelete) {
//                        holder.getView(R.id.iv_delete).setVisibility(View.VISIBLE);
//                    } else {
//                        holder.getView(R.id.iv_delete).setVisibility(View.GONE);
//                    }
//                }
//
//            }
//        };
//
//
//        mRvPayment.setLayoutManager(new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false) {
//            @Override
//            public boolean canScrollVertically() {
//                return false;
//            }
//        });
//        mRvPayment.setAdapter(mCustomImageAdapter);
//    }

//    private void showDeleteConfirmDialog(final int position) {
//        ConfirmDialog mConfirmDialog = new ConfirmDialog(mContext, new ConfirmDialog.OnBottomButtonClickListener() {
//            @Override
//            public void onLeftButtonClick(View view) {
//            }
//
//            @Override
//            public void onRightButtonClick(View view) {
//                mImageList.remove(position);
//                if (!mImageList.contains(mImageItem)) {
//                    mImageList.add(mImageItem);
//                }
//                mCustomImageAdapter.notifyDataSetChanged();
//            }
//
//        });
//        mConfirmDialog.showDialog("确认删除？", "取消", "确认");
//    }
//
//    //Allen:选择上传图片方式
//    private void showPopupWindow() {
//        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_album_camera, null);
//        // 强制隐藏键盘
//        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
//        if (mPopupWindow == null) {
//
//            ImagePicker imagePicker = ImagePicker.getInstance();
//            imagePicker.setImageLoader(new GlideImageLoader());
//            imagePicker.setCrop(false);
//            imagePicker.setMultiMode(true);
//            imagePicker.setShowCamera(true);
//
//            mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//            mPopupWindow.setFocusable(true);
//            mPopupWindow.setOutsideTouchable(true);
//            /* mPopupWindow.setBackgroundDrawable(new BitmapDrawable());*/
//            mPopupWindow.setAnimationStyle(R.style.AnimationBottomDialog);
//            mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
//                @Override
//                public boolean onTouch(View view, MotionEvent motionEvent) {
//                    if (motionEvent.getAction() == MotionEvent.ACTION_OUTSIDE) {
//                        mPopupWindow.dismiss();
//                        return true;
//                    }
//                    return false;
//                }
//            });
//            mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//                @Override
//                public void onDismiss() {
//                    WindowUtil.setPopWindowBackgroundAlpha(AgentExitActivity.this, 1f);
//                }
//            });
//            view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    mPopupWindow.dismiss();
//                }
//            });
//            view.findViewById(R.id.btn_camera).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    mPopupWindow.dismiss();
//                    checkPermission(new CheckPermListener() {
//                        @Override
//                        public void superPermission() {
//                            Intent intent = new Intent(mContext, ImageGridActivity.class);
//                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
//                            intent.putExtra(ImageGridActivity.EXTRAS_IMAGES, (Serializable) mImageList);
//                            startActivityForResult(intent, REQUEST_CAMERA);
//                            mPopupWindow.dismiss();
//                        }
//                    }, R.string.ask_again, Manifest.permission.CAMERA);
//                }
//            });
//            view.findViewById(R.id.btn_album).setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    mPopupWindow.dismiss();
//                    checkPermission(new CheckPermListener() {
//                        @Override
//                        public void superPermission() {
//                            ImagePicker.getInstance().setSelectLimit(1);
//                            Intent intent = new Intent(mContext, ImageGridActivity.class);
//                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, false);
//                            startActivityForResult(intent, REQUEST_ALBUM);
//                            mPopupWindow.dismiss();
//                        }
//                    }, R.string.ask_again, Manifest.permission.READ_EXTERNAL_STORAGE);
//                }
//            });
//        }
//        WindowUtil.setPopWindowBackgroundAlpha(AgentExitActivity.this, 0.7f);
//        mPopupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);
//    }
}
